let secret_code = ''
const app = getApp()
Page({
  data: {
    countDownVisible: false,
    mobile: '13900000000',
    code: ''
  },
  onLoad({
    redirectURL
  }) {
    this.setData({
      redirectURL
    })
  },
  // 验证手机号
  verifyMoblie() {
    const reg = /^1[2-9][0-9]{9}$/
    const valid = reg.test(this.data.mobile.trim())
    if (!valid) wx.utils.toast('请填写正确的手机号码')
    return valid
  },
  // 点击获取验证码
  async getCode() {
    if (!this.verifyMoblie()) return
    // 请求获取手机验证码
    const {
      code,
      message,
      data
    } = await wx.http.get('/code', {
      mobile: this.data.mobile.trim()
    })
    if (code !== 10000) {
      return wx.utils.toast(message)

    }
    wx.utils.toast('发送成功，请查收短信')
    this.setData({
      countDownVisible: true
    })
    secret_code = data.code
  },
  // 复制验证码
  copyCode() {
    wx.setClipboardData({
      data: secret_code
    })
  },
  // 验证码正则
  verifyCode() {
    const reg = /^\d{6}$/
    const valid = reg.test(this.data.code.trim())
    if (!valid) {
      return wx.utils.toast('请填写正确的验证码')
    }
    return valid

  },
  // 提交表单
  async submitForm() {
    if (!this.verifyMoblie()) return
    if (!this.verifyCode()) return
    const {
      code,
      data,
      message
    } = await wx.http.post('/login', {
      mobile: this.data.mobile.trim(),
      code: this.data.code.trim()
    })
    if (code !== 10000) {
      return wx.utils.toast(message)
    }
    app.setToken(data.token, data.refreshToken)

    wx.redirectTo({
      url: this.data.redirectURL,
    })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
})